package music;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.beaglebuddy.mp3.MP3;
import com.example.administrator.sdscanner.MainActivity;

import org.apache.commons.codec.binary.Base64;
import org.litepal.crud.DataSupport;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import bean.MP3Info;
import bean.MusicPattern;
import util.Util;

/**
 * Created by Administrator on 2017/3/2.
 */

public class Music {
    // 当前播放标识
    public static boolean isPlaying = false;
    // 当前列表播放索引
    public static int index = 0;
    // 歌曲数据缓存
    public static List<MP3Info> cacheList = new ArrayList<>() ;
    // 当前播放列表
    public static List<MP3Info> currentList = new ArrayList<>();
    // 歌手列表
    public static List<List<MP3Info>> artistList = new ArrayList<>();
    // 专辑列表
    public static List<List<MP3Info>> albumList = new ArrayList<>();
    // 文件夹列表
    public static List<List<MP3Info>> floderList = new ArrayList<>();
    // 播放器
    public static MediaPlayer m;
    // 播放器管理工具
    public static AudioManager mManager = null;
    // 播放模式(0->循环播放, 1->单曲循环, 2-随机播放)
    public static int playPattern = MusicPattern.cyclicPattern.getCode();
    // 最大音量
    public static int maxVolume;
    // 当前音量
    public static int currentVolume;
    // webView 传递数据
    public static WebView webView;
    // 随机播放列表
    private static List<Integer> randomList = new ArrayList<>();
    // 播放第一首歌
    private static boolean isFist = true;
    // 进度条滑动标识
    private static boolean isSlide = false;
    // 定时器
    private static Timer timer;
    // 定时器任务
    private static TimerTask timerTask;
    private static Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int currentTime = (Integer)msg.obj;
            webView.loadUrl("JavaScript:UIFrame.updateNowTime('" + Util.secondToTime(currentTime) + "')");
            webView.loadUrl("JavaScript:UIFrame.updateProView('.play-page .ms-audio-time', (" + currentTime + " / MusicInfo.duration * 100).toFixed(0)+'%')");
            webView.loadUrl("JavaScript:UIFrame.updateLyric(" + currentTime + ")");
            webView.loadUrl("JavaScript:MusicInfo.currentTime=" + currentTime + ";");
        }
    };

    public Music(AudioManager mManager) {
        this.mManager = mManager;
    }

    public Music() {
    }

    @JavascriptInterface
    public static boolean isSlide() {
        return isSlide;
    }

    @JavascriptInterface
    public static void setIsSlide(boolean isSlide) {
        Music.isSlide = isSlide;
    }

    @JavascriptInterface
    public static void delMusic(int index, boolean del){
        if (del){
            File file  = new File(cacheList.get(index).getPath());
            boolean delSign = file.delete();
            if (!delSign){
                Toast.makeText(MainActivity.getContext(), "权限不足，无法删除本地文件", Toast.LENGTH_SHORT);
            }
        }
        DataSupport.delete(MP3Info.class, cacheList.get(index).getId());
        cacheList.remove(index);

    }

    /**
     *  下一首歌曲
     */
    public static void nextMusic(){
        switch (playPattern){
            case 0:
                index = index + 1 >= currentList.size() ? 0 : index + 1;
                playing();
                break;
            case 1:
                index = index + 1 >= currentList.size() ? 0 : index + 1;
                playing();
                break;
            case 2:
                randomPattern();
                break;
            default: cyclicPattern();
                break;
        }
    }

    /**
     *  上一首歌曲
     */
    public static void preMusic(){
        switch (playPattern){
            case 0:
                index = index - 1 <= -1 ? currentList.size() - 1 : index - 1;;
                break;
            case 1:
                index = index - 1 <= -1 ? currentList.size() - 1 : index - 1;;
                break;
            case 2:
                randomPattern();
                break;
            default: cyclicPattern();
                break;
        }
        playing();
    }

    /**
     * 按播放模式进行播放
     */
    public static void playPatter(){
        switch (playPattern){
            case 0:
                cyclicPattern();
                break;
            case 1:
                singlePattern();
                break;
            case 2:
                randomPattern();
                break;
            default: cyclicPattern();
                break;
        }
    }

    /**
     * @param index 索引
     * 播放指定索引音乐
     *
     */
    public static void play(int index){
        Music.index = index;
        if (Music.playPattern == MusicPattern.randomPattern.getCode()){
            randomList.add(index);
        }
        playing();
    }

    /**
     * @param pattern 播放模式
     * 改变播放模式
     */
    @JavascriptInterface
    public static void changePattern(int pattern){
        Music.playPattern = pattern;
        if (pattern == MusicPattern.randomPattern.getCode()){
            randomList.clear();
        }
    }

    /**
     * 循环播放
     */
    private static void cyclicPattern(){
        index = index + 1 >= currentList.size() ? 0 : index + 1;
        playing();
    }

    /**
     * 单曲循环
     */
    private static void singlePattern(){
        playing();
    }

    /**
     * 随机播放
     */
    private static void randomPattern(){
        int number;
        Random random = new Random();
        if (randomList.size() <= currentList.size()){
            do{
                number = random.nextInt(currentList.size() - 1);
            } while (randomList.contains(number));
            randomList.add(number);
            index = number;
            playing();
        } else {
            randomList.clear();
        }
    }

    /**
     *  播放音乐
     */
    private static void playing(){
        try{
            m.stop();
            m.reset();
            m.setDataSource(currentList.get(index).getPath());
            m.prepare();

            // 当前播放音乐的封面
            MP3 mp3 = new MP3(currentList.get(index).getPath());
            String img = "img/default.jpg";
            if (!mp3.hasErrors()){
                if (mp3.getPictures().size() >= 1) {
                    try {
                        img = "data:" + mp3.getPictures().get(0).getMimeType() + ";base64," + new String(Base64.encodeBase64(mp3.getPictures().get(0).getImage()));
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }

            webView.loadUrl("JavaScript:UIFrame.updatePlayListUI(" + index + ");");
            webView.loadUrl("JavaScript:UIFrame.scrollToPlayUI(" + index + ");");
            webView.loadUrl("JavaScript:UIFrame.selectlocalList(UIFrame.localMusic, " + cacheList.indexOf(currentList.get(index)) + ");");
            webView.loadUrl("JavaScript:UIFrame.selectlocalList('#artist-music-list', " + getArtistIndex(currentList.get(index).getArtist()) + ");");
            webView.loadUrl("JavaScript:UIFrame.selectlocalList('#album-music-list', " + getAlbumIndex(currentList.get(index).getAlbum()) + ");");
            webView.loadUrl("JavaScript:UIFrame.selectlocalList('#floder-music-list', " + getFloderIndex(currentList.get(index).getPath()) + ");");
            webView.loadUrl("JavaScript:updateMusicInfo(" + index + ", '" + img +"');");


            // 初始化播放器
            if (isFist) {
                // 启动定时器获取播放进度
                timer = new Timer();
                timerTask = new TimerTask() {
                    @Override
                    public void run() {
                        if (!isSlide && m.isPlaying()) {
                            int currentTime = (int) Math.floor(m.getCurrentPosition() / 1000);
                            Message msg = new Message();
                            msg.obj = currentTime;
                            handler.sendMessage(msg);
                        }
                    }
                };
                timer.schedule(timerTask, 0, 100);
                isFist = false;
            }
            if (isPlaying){
                m.start();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 读取歌词
     * @return 歌词文本
     */
    @JavascriptInterface
    public static String getLyric() {

        File file = (MainActivity.getContext().getFileStreamPath(currentList.get(index).getName() + ".lrc"));
        if (file.exists()) {
            try {
                BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
                StringBuffer sb = new StringBuffer();
                String temp;
                while ((temp = bf.readLine()) != null) {
                    sb.append(temp + "\\n");
                }
                bf.close();

                return sb.toString();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return "暂无歌词";
    }

    /**
     * 获得歌手列表index
     * @return 索引
     */
    private static int getArtistIndex(String artist){
        int index = 0;

        for (List<MP3Info> list : artistList){
            if (list.get(0).getArtist().equals(artist)){
                index = artistList.indexOf(list);
                break;
            }
        }

        return index;
    }

    /**
     * 获得专辑列表index
     * @return 索引
     */
    private static int getAlbumIndex(String album){
        int index = 0;

        for (List<MP3Info> list : albumList){
            if (list.get(0).getAlbum().equals(album)){
                index = albumList.indexOf(list);
                break;
            }
        }

        return index;
    }

    /**
     * 获得文件夹列表index
     * @return 索引
     */
    private static int getFloderIndex(String path){
        int index = 0;

        for (List<MP3Info> list : floderList){
            if (list.get(0).getPath().substring(0, list.get(0).getPath().lastIndexOf('/')).equals(path.substring(0, path.lastIndexOf('/')))){
                index = floderList.indexOf(list);
                break;
            }
        }

        return index;
    }
}
